package leetcode.medium.limit100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yaoyao1.liu@zhaopin.com.cn
 * @since 2022-11-10 16:07
 **/
public class No71 {

    public static void main(String[] args) {
        No71 no71 = new No71();
        String simplifyPath = no71.simplifyPath("/a/./b/../../c/");
        System.out.println(simplifyPath);
    }

    public String simplifyPath(String path) {
        char[] chars = path.toCharArray();

        Map<String, Integer> map = new HashMap<>();

        map.put(".", 0);
        map.put("..", -1);
        map.put("/", 1);
        map.put("//", 1);
        StringBuilder stringBuilder = new StringBuilder();
        List<String> pathList = new ArrayList<>();
        String[] split = path.split("/");
        for (String s : split) {
            if (s.length() == 0) {
                continue;
            }
            boolean containsKey = map.containsKey(s);
            if (containsKey) {
                Integer integer = map.get(s);
                if (integer == -1 && pathList.size() > 0) {
                    pathList.remove(pathList.size() - 1);
                }
            } else {
                pathList.add(s);
            }
        }
        stringBuilder.append("/");
        for (String s : pathList) {
            stringBuilder.append(s).append("/");
        }
        if (stringBuilder.length() > 1) {
            return stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
        }else {
            return stringBuilder.toString();
        }
    }
}
